package com.dx.wx.service.impl;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.dx.wx.service.DxWxAppService;
import com.dx.wx.service.DxUserService;
import com.dx.wx.util.DxUtil;
import com.ejlchina.data.Array;
import com.ejlchina.data.Mapper;
import com.yf.response.R;
import com.yf.response.RRException;
import com.yf.service.TokenService;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Service
public class DxUserServiceImpl implements DxUserService {


    @Autowired
    private DxWxAppService dxWxAppService;

    @Autowired
    private TokenService tokenService;


    @Override
    public R loginByWx(String code, String appId) {
        WxMaJscode2SessionResult result = dxWxAppService.getWxId(code,appId);
        Mapper userMapper = findByWxId(result.getOpenid(), result.getUnionid());
        if (userMapper != null) {
            if (userMapper.getInt("user_status__c") != 1) {
                throw new RRException("审核中");
            }

            return R.ok(tokenService.createToken(userMapper.getLong("field_z79am__c"))).putExtra("user", userMapper.toString());
        }
        return R.ok().putExtra("wxUser", result);
    }

    @Override
    public R loginByTest(String phone, String appId) {
        Mapper userMapper = findByMobile(phone,appId);
        return R.ok(tokenService.createToken(userMapper.getLong("field_z79am__c"))).putExtra("user", userMapper.toString());
    }

    @Override
    public R loginByPhone(String code, String openId, String unionId, String appId) {
        if (code == null) {
            return R.ok();
        }

//        WxMaPhoneNumberInfo phoneNumberInfo = dxWxAppService.getWxPhone(code);
//        String phone = phoneNumberInfo.getPhoneNumber()
        //微信无法自动获取手机号了
        String phone = code;
        Mapper userMapper = findByMobile(phone,appId);
        if (userMapper != null) {
//            if (!userMapper.getString("life_status").equals("normal")) {
//                throw new RRException("审核中");
//            }
            if (userMapper.getInt("user_status__c") != 1) {
                throw new RRException("审核中");
            }
            //更新用户信息
            updateUserWxInfo(userMapper, openId, unionId);
            //获取新的mapper
            userMapper = findByMobile(phone);
            if (userMapper == null) {
                throw new RRException("CRM再获取用户失败!");
            }
            return R.ok(tokenService.createToken(userMapper.getLong("field_z79am__c"))).putExtra("user", userMapper.toString());
        }else { //如果是游客直接注册

        }
        return R.ok().putExtra("phone",phone);
    }

    private void updateUserWxInfo(Mapper userMapper, String openId, String unionId) {
        Map data = new HashMap();
        data.put("_id", userMapper.getString("_id"));
        data.put("open_id__c", openId);
        data.put("union_id__c", unionId);
        updateUser(data);
    }

    @Override
    public void updateUser(Map data) {
        data.put("dataObjectApiName", "object_LbL1f__c");
        DxUtil.update(DxUtil.createMergeData(data));
    }

    /**
     * 上级就是代表手机号
     * 上上级就是主管手机号
     * crm自动通过owner设置的 我们只要设置owner即可
     * @param data
     * @param appId
     */

    @Override
    public void saveUser(Map data, String appId) {
        if (data.get("field_Rh3vp__c").equals("4")) {//消费者
//            String code = (String) data.get("code");
//            WxMaJscode2SessionResult codeResult = dxWxAppService.getWxId(code);

            data.put("owner", Arrays.asList("FSUID_BD13458744388673403F8B3C317FAA43"));
            data.put("shop_phone__c", data.get("field_O820j__c"));//店员手机号
//            data.put("open_id__c",codeResult.getOpenid());
//            data.put("union_id__c",codeResult.getUnionid());
        } else {
            //负责人转换
            data.put("owner", Arrays.asList(DxUtil.getOpenUserId((String) data.get("field_O820j__c"))));
        }
        //更新APPID
        data.put("app_id__c",appId);
        data.put("dataObjectApiName", "object_LbL1f__c");
        DxUtil.save(DxUtil.createMergeData(data));
    }

    @Override
    public void saveUser(String phone, String role, String topPhone, String openId,String unionId) {
        Map data = new HashMap();
        if (role.equals("4")) {//消费者
            data.put("owner", Arrays.asList("FSUID_BD13458744388673403F8B3C317FAA43"));
            data.put("shop_phone__c",topPhone);//店员手机号
            data.put("field_O820j__c",topPhone);//店员手机号
            data.put("field_z79am__c",phone);//自己的手机号
            data.put("field_Rh3vp__c",role);//角色
            data.put("user_status__c",1);//状态
            data.put("open_id__c",openId);
            data.put("union_id__c",unionId);
        } else {
            //负责人转换
            data.put("owner", Arrays.asList(DxUtil.getOpenUserId(topPhone)));
        }
        data.put("dataObjectApiName", "object_LbL1f__c");
        DxUtil.save(DxUtil.createMergeData(data));
    }

    @Override
    public Mapper findByWxId(String openId, String unionId) {
        //open_id__c  union_id__c
        Map filter = new HashMap<>();
        String filedName = "open_id__c";
        String filedValue = openId;
        if (unionId != null && !unionId.equals("")) {
            filedName = "union_id__c";
            filedValue = unionId;
        }
        filter.put("operator", "EQ");
        filter.put("field_name", filedName);
        filter.put("field_values", Arrays.asList(filedValue));
        Map data = DxUtil.createSearchData(filter);
        data.put("dataObjectApiName", "object_LbL1f__c");
        Mapper mapper = DxUtil.findOne(data);
        return mapper;
    }

    @Override
    public Mapper findByMobile(String mobile) {
        Map filter = new HashMap<>();
        filter.put("operator", "EQ");
        filter.put("field_name", "field_z79am__c");
        filter.put("field_values", Arrays.asList(mobile));
        Map data = DxUtil.createSearchData(filter);
        data.put("dataObjectApiName", "object_LbL1f__c");
        Mapper mapper = DxUtil.findOne(data);
        return mapper;
    }

    @Override
    public Mapper findByMobile(String mobile, String appId) {
        Map filter = new HashMap<>();
        filter.put("operator", "EQ");
        filter.put("field_name", "field_z79am__c");
        filter.put("field_values", Arrays.asList(mobile));
        Map appIdFilter = DxUtil.addAppIdFilter(appId);
        Map data = DxUtil.createSearchData(filter,appIdFilter);
        data.put("dataObjectApiName", "object_LbL1f__c");
        Mapper mapper = DxUtil.findOne(data);
        return mapper;
    }

    @Override
    public Mapper findById(String Id) {
        Map filter = new HashMap<>();
        filter.put("operator", "EQ");
        filter.put("field_name", "_id");
        filter.put("field_values", Arrays.asList(Id));
        Map data = DxUtil.createSearchData(filter);
        data.put("dataObjectApiName", "object_LbL1f__c");
        Mapper mapper = DxUtil.findOne(data);
        return mapper;
    }

    @Override
    public void updateUserShop(String shopId, String[] userIds) {
        for (String userId : userIds) {
            Mapper user = findById(userId);
            Map map = new HashMap();
            map.put("_id", user.getString("_id"));
            map.put("field_7Q38t__c", shopId);
            updateUser(map);
        }
    }

    @Override
    public Array findGoodsByUser(Long phone) {
        Mapper user = findByMobile(String.valueOf(phone));
        String id = user.getString("_id");
        Map filter = new HashMap();
        filter.put("field_name", "field_Dw863__c");
        filter.put("field_values", Arrays.asList(id));
        filter.put("operator", "EQ");
        Map data = DxUtil.createSearchData(filter);
        data.put("dataObjectApiName", "object_7Fe9h__c");
        return DxUtil.findSimple(data);
    }

    @Override
    public Array findByShop(Long phone, String id) {
        if (id == null || id.equals("undefined")) {
            Mapper userMapper = findByMobile(String.valueOf(phone));
            id = userMapper.getString("field_7Q38t__c");
        }
        //根据药店ID查找
        Map filter = new HashMap();
        filter.put("field_name", "field_7Q38t__c");
        filter.put("field_values", Arrays.asList(id));
        filter.put("operator", "EQ");
        Map sf = new HashMap();
        sf.put("field_name", "user_status__c");
        sf.put("field_values", 2);
        sf.put("operator", "N");
        Map data = DxUtil.createSearchData(filter, sf);
        data.put("dataObjectApiName", "object_LbL1f__c");
        Array array = DxUtil.findSimple(data);
        return array;
    }

    @Override
    public Array findMyShopUser(Long phone, Long startDate, Long endDate) {
        Mapper mapper = findByMobile(String.valueOf(phone));
        Map filter = new HashMap();
        if (mapper.getInt("field_Rh3vp__c") == 2) {//主管
            filter.put("field_name", "field_rtIpu__c");
        } else {
            filter.put("field_name", "field_5h7D5__c");
        }
        filter.put("field_values", phone);
        filter.put("operator", "EQ");
        Map sf = new HashMap();
        sf.put("field_name", "user_status__c");
        sf.put("field_values", 2);
        sf.put("operator", "N");
        Map data;
        if (startDate != null && endDate != null) {
            Map dateStartFilter = new HashMap();
            Map dateEndFilter = new HashMap();
            //传入时间
            dateStartFilter.put("field_name", "create_time");
            dateStartFilter.put("field_values", Arrays.asList(startDate));
            dateStartFilter.put("operator", "GTE");//大于等于
            dateEndFilter.put("field_name", "create_time");
            dateEndFilter.put("field_values", Arrays.asList(endDate));
            dateEndFilter.put("operator", "LTE");//小于等于s
            data = DxUtil.createSearchData(sf, filter, dateStartFilter, dateEndFilter);
        } else {
            data = DxUtil.createSearchData(sf, filter);
        }
        data.put("dataObjectApiName", "object_LbL1f__c");
        Array array = DxUtil.findSimple(data);
        return array;
    }


    @Override
    public Array findByTop(Long phone) {
        Map filter = new HashMap();
        filter.put("field_name", "field_5h7D5__c");
        filter.put("field_values", Arrays.asList(phone));
        filter.put("operator", "EQ");
        Map sf = new HashMap();
        sf.put("field_name", "user_status__c");
        sf.put("field_values", 2);
        sf.put("operator", "N");
        Map data = DxUtil.createSearchData(filter, sf);
        data.put("dataObjectApiName", "object_LbL1f__c");
        Array array = DxUtil.findSimple(data);
        return array;
    }

    @Override
    public Array findByTop(Long phone, String appId) {
        Map filter = new HashMap();
        filter.put("field_name", "field_5h7D5__c");
        filter.put("field_values", Arrays.asList(phone));
        filter.put("operator", "EQ");
        Map sf = new HashMap();
        sf.put("field_name", "user_status__c");
        sf.put("field_values", 2);
        sf.put("operator", "N");
        Map appFilter = DxUtil.addAppIdFilter(appId);
        Map data = DxUtil.createSearchData(filter, sf,appFilter);
        data.put("dataObjectApiName", "object_LbL1f__c");
        Array array = DxUtil.findSimple(data);
        return array;
    }

    @Override
    public Array findByTopTop(Long phone, String appId) {
        Map filter = new HashMap();
        filter.put("field_name", "field_rtIpu__c"); //主管手机号
        filter.put("field_values", Arrays.asList(phone));
        filter.put("operator", "EQ");
        Map sf = new HashMap();
        sf.put("field_name", "user_status__c");
        sf.put("field_values", 2);
        sf.put("operator", "N");
        Map appFilter = DxUtil.addAppIdFilter(appId);
        Map data = DxUtil.createSearchData(filter, sf,appFilter);
        data.put("dataObjectApiName", "object_LbL1f__c");
        Array array = DxUtil.findSimple(data);
        return array;
    }

    @Override
    public Array findByMan(Long phone) {
        Map filter = new HashMap();
        filter.put("field_name", "manager_phone__c");
        filter.put("field_values", Arrays.asList(phone));
        filter.put("operator", "EQ");
        Map sf = new HashMap();
        sf.put("field_name", "user_status__c");
        sf.put("field_values", 2);
        sf.put("operator", "N");
        Map data = DxUtil.createSearchData(filter, sf);
        data.put("dataObjectApiName", "object_LbL1f__c");
        Array array = DxUtil.findSimple(data);
        return array;
    }

    @Override
    public void check(String phone, Integer type) {
        Mapper mapper = findByMobile(phone);
        Map data = new HashMap();
        data.put("_id", mapper.getString("_id"));
        if (type == 0) {
            data.put("user_status__c", 2);//拒绝
        } else {
            data.put("user_status__c", 1);//通过
        }
        updateUser(data);
    }


}
